﻿using System;
using System.Collections.Generic;
using System.Text;
using BlueLotus7.Common;
using System.Runtime.Serialization;

namespace BlueLotus7.Contract
{
    [DataContract]
    [KnownType(typeof(Guid))]
    public class BaseText : IValidate, ICloneable
    {
        #region Fields

        [DataMember]
        protected Guid textKey;

        [DataMember]
        protected string textContent;

        [DataMember]
        protected DateTime createdStamp;

        [DataMember]
        protected DateTime lastUpdatedStamp;

        #endregion

        #region Property

        public Guid TextKey
        {
            get { return textKey; }
        }

        public string TextContent
        {
            get { return textContent; }
            set
            {
                if (value == null)
                {
                    value = string.Empty;
                }
                textContent = value;
                lastUpdatedStamp = DateTime.Now;
            }
        }

        public DateTime CreatedStamp
        {
            get { return createdStamp; }
        }

        public DateTime LastUpdatedStamp
        {
            get { return lastUpdatedStamp; }
        }

        #endregion

        public BaseText(string content)
        {
            this.textKey = Guid.NewGuid();
            this.textContent = content == null ? string.Empty : content;
            this.createdStamp = this.lastUpdatedStamp = DateTime.Now;
        }

        public BaseText(Guid textKey, string textContent, DateTime createdStamp, DateTime lastUpdatedStamp)
        {
            this.textKey = textKey;
            this.textContent = textContent == null ? string.Empty : textContent;
            this.createdStamp = createdStamp;
            this.lastUpdatedStamp = lastUpdatedStamp;
        }

        public override string ToString()
        {
            return textContent;
        }

        #region IValidate 成员

        public bool IsValid
        {
            get
            {
                try
                {
                    Validate();
                    return true;
                }
                catch
                {
                    return false;
                }
            }
        }

        public virtual void Validate()
        {
            if (this.createdStamp > this.lastUpdatedStamp)
            {
                throw new InvalidObjectException("lastUpdatedStamp");
            }
        }

        #endregion

        #region ICloneable 成员

        public virtual object Clone()
        {
            return new BaseText(this.textKey, this.textContent, this.createdStamp, this.lastUpdatedStamp);
        }

        #endregion
    }
}
